<template>
  <basePages>
    <view class="device-detail">
      <view class="device-info" v-if="deviceInfo">
        <view class="device-header">
          <view class="device-icon">
            <uni-icons :type="getDeviceIcon(deviceInfo.deviceType)" size="40" color="#409EFF"></uni-icons>
          </view>
          <view class="device-title">
            <text class="name">{{ deviceInfo.metaData?.name || getDeviceTypeName(deviceInfo.deviceType) }}</text>
            <text class="sn">SN: {{ deviceInfo.sn }}</text>
          </view>
          <view class="device-status" :class="{ 'status-online': deviceInfo.status === 'active' }">
            {{ deviceInfo.status === 'active' ? '在线' : '离线' }}
          </view>
        </view>

        <view class="info-list">
          <view class="info-item">
            <text class="label">设备类型</text>
            <text class="value">{{ getDeviceTypeName(deviceInfo.deviceType) }}</text>
          </view>
          <view class="info-item">
            <text class="label">MAC地址</text>
            <text class="value">{{ deviceInfo.mac }}</text>
          </view>
          <view class="info-item" v-if="deviceInfo.bindTime">
            <text class="label">绑定时间</text>
            <text class="value">{{ formatDate(deviceInfo.bindTime) }}</text>
          </view>
          <view class="info-item">
            <text class="label">最后同步</text>
            <text class="value">{{ formatDate(deviceInfo.lastSyncTime) }}</text>
          </view>
          <view class="info-item" v-if="deviceInfo.metaData?.note">
            <text class="label">备注信息</text>
            <text class="value">{{ deviceInfo.metaData.note }}</text>
          </view>
        </view>
      </view>
       <view v-else class="empty-state">
          <text>设备信息加载中或不存在。</text>
        </view>

      <view class="action-buttons" v-if="deviceInfo">
        <button class="action-btn sync" @click="syncDeviceData">
          <uni-icons type="refresh" size="20" color="#409EFF"></uni-icons>
          <text>同步数据</text>
        </button>
        <button class="action-btn unbind" @click="handleUnbind">
          <uni-icons type="trash" size="20" color="#F56C6C"></uni-icons>
          <text>解绑设备</text>
        </button>
      </view>
    </view>
  </basePages>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useDeviceStore } from '../../../store/modules/useDeviceStore';

const deviceStore = useDeviceStore();
const currentDeviceSN = ref(null);

// 从 store 中获取设备详情 (计算属性)
const deviceInfo = computed(() => {
    if (!currentDeviceSN.value) return null;
    return deviceStore.getDeviceBySN(currentDeviceSN.value);
});

// 同步设备状态和信息
const syncDeviceData = async () => {
    if (!currentDeviceSN.value) return;
  try {
    uni.showLoading({ title: '同步中...' });
    await deviceStore.syncDeviceStatusAndInfo(currentDeviceSN.value);
    uni.hideLoading();
    uni.showToast({
      title: '同步成功',
      icon: 'success'
    });
  } catch (error) {
    uni.hideLoading();
    console.error('Error syncing device data:', error);
    uni.showToast({
      title: error.message || '同步失败',
      icon: 'none'
    });
  }
};

// 解绑设备
const handleUnbind = () => {
    if (!currentDeviceSN.value) return;
  uni.showModal({
    title: '提示',
    content: '确定要解绑该设备吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await deviceStore.unbindDevice(currentDeviceSN.value);
          uni.showToast({
            title: '解绑成功',
            icon: 'success'
          });
          setTimeout(() => {
            uni.navigateBack();
          }, 1000);
        } catch (error) {
          uni.showToast({
            title: error.message || '解绑失败',
            icon: 'none'
          });
        }
      }
    }
  });
};

// 获取设备图标 (保持不变)
const getDeviceIcon = (type) => {
  const iconMap = {
    wearable: 'watch',
    BPMonitor: 'heart',
    BGMeter: 'scale',
    spO2Monitor: 'heart',
    ECGMonitor: 'heart',
    BFPMonitor: 'scale',
    Thermometer: 'thermometer',
    other: 'device'
  };
  return iconMap[type] || 'device';
};

// 获取设备类型名称 (保持不变)
const getDeviceTypeName = (type) => {
  const nameMap = {
    wearable: '智能手表',
    BPMonitor: '血压计',
    BGMeter: '血糖仪',
    spO2Monitor: '血氧仪',
    ECGMonitor: '心电图仪',
    BFPMonitor: '体脂秤',
    Thermometer: '体温计',
    other: '其他设备'
  };
  return nameMap[type] || '未知设备';
};

// 格式化日期 (保持不变)
const formatDate = (date) => {
  if (!date) return '暂无数据';
  const d = new Date(date);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
};

onMounted(() => {
  // 从本地存储获取 deviceSN
  currentDeviceSN.value = uni.getStorageSync('currentDeviceSN');  
});

// 监听 deviceList 的变化，如果当前设备信息有更新，则更新显示
// watch(() => deviceStore.deviceList, () => {
//     if (currentDeviceSN.value) {
//         deviceInfo.value = deviceStore.getDeviceBySN(currentDeviceSN.value);
//     }
// }, { deep: true });

</script>

<style lang="scss" scoped>
.device-detail {
  padding: 20rpx;
  min-height: 100vh;
  background-color: #f8fafc;
}

.device-info {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.empty-state {
    text-align: center;
    padding: 40rpx 0;
    color: #999;
    font-size: 28rpx;
}

.device-header {
  display: flex;
  align-items: center;
  margin-bottom: 4px;

  .device-icon {
    width: 100rpx;
    height: 100rpx;
    background: #ecf5ff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20rpx;
  }

  .device-title {
    flex: 1;

    .name {
      font-size: 32rpx;
      font-weight: 500;
      color: #333;
      display: block;
      margin-bottom: 8rpx;
    }

    .sn {
      font-size: 24rpx;
      color: #999;
    }
  }
}

.device-status {
  font-size: 24rpx;
  color: #909399;
  padding: 4rpx 16rpx;
  border-radius: 20rpx;
  background: #f4f4f5;

  &.status-online {
    color: #67c23a;
    background: #f0f9eb;
  }
}

.info-list {
  .info-item {
    display: flex;
    justify-content: space-between;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .label {
      font-size: 28rpx;
      color: #666;
    }

    .value {
      font-size: 28rpx;
      color: #333;
    }
  }
}

.action-buttons {
  display: flex;
  gap: 20rpx;

  .action-btn {
    flex: 1;
    height: 88rpx;
    border-radius: 44rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    gap: 8rpx;

    &.sync {
      background: #ecf5ff;
      color: #409EFF;
    }

    &.unbind {
      background: #fef0f0;
      color: #F56C6C;
    }

    &:active {
      opacity: 0.8;
    }
  }
}
</style>
